import requests
import  login_info.login_info as login
from tools.get_sql import getsql,get_all_dict,get_small_dict,trim_num_full,trim_num_small,del_total
from tools.log_op import write_log
def step_1(ins, sql_cmd):
    # 模拟浏览器，把SQL命令发送给服务器
    # 返回SQL命令的实例ID
    headers_1 = login.heard_sql_id
    if ins.cookies != '':
        headers_1['Cookie'] = ins.cookies
    # 发送的数据
    data = login.data
    if sql_cmd:
        data['actionConf']['sql'] = sql_cmd
    result_1 = requests.post(url=ins.send_job_url, headers=headers_1, json=data)

    if result_1.status_code == 200:
        result_json = result_1.json()
        status = result_json['retCode']
        if status == 200:
            instanceid = result_json['retData']['instanceId']
        print('服务器接受sql成功(step1 成功)')
        return instanceid
    else:
        raise Exception('登陆错误，错误码为：', result_1.status_code)

def step_2(ins, instanceid):
    # 接收实例ID，查询执行状态
    headers_2 = login.header2
    if ins.cookies != '':
        headers_2['Cookie'] = ins.cookies

    url_2 = ins.chk_job_stats_url_head.format(instanceid)
    result_2 = requests.get(url=url_2, headers=headers_2)

    if result_2.status_code == 200:
        sql_step = result_2.json()
        if(sql_step['retData']['stmtProgresses'][0]['state']=='FINISHED'):
            success_sql = str(getsql(result_2.text))
            write_log(success_sql)
        poll_cont = sql_step['retData']['stmtProgresses'][0]

        print('轮询中：(step2)')
        print('retCode: ',sql_step['retCode'],' state:',poll_cont['state'],' sql:',poll_cont['statement'])
    else:
        print(result_2.status_code)

    state = sql_step['retData']['stmtProgresses'][0]['state']
    return state

def step_3(ins, instanceid):
    # 接收实例ID，获取执行结果
    headers_3 = login.headers_3
    if ins.cookies != '':
        headers_3['Cookie'] = ins.cookies

    url_3 = ins.get_job_result_url_head.format(instanceid)
    result_3 = requests.get(url=url_3, headers=headers_3)
    if result_3.status_code == 200:
        result = result_3.text
        print('get sql result success')
        print(result)
        # print(type(result))
        return result_3.json()

    else:
        print(result_3.status_code)
